package com.moter.demo01.juc.alllocks.fairlock;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class FairLock {
    private  volatile LinkedBlockingQueue<Thread> queue = new LinkedBlockingQueue<>();
    private volatile int state;
    public FairLock(){
        state = 0;
    }
    public synchronized void lock(){
        if(queue.size()<=0&&state==0){
        }else{
            Thread thread = Thread.currentThread();
            try {
                queue.put(thread);
                LockSupport.park();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        state=1;
        queue.forEach(System.out::println);
    }
    public void unlock(){
        try {
            if(queue.size()>0) {
                Thread take = queue.take();
                System.out.println(take.getName()+"\t"+take.getState());
                TimeUnit.MICROSECONDS.sleep(100);
                LockSupport.unpark(take);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        state=0;
    }

    public static void main(String[] args) throws InterruptedException {
        FairLock fairLock = new FairLock();
        for (int i = 0; i <10 ; i++) {
            int finalI = i;
            new Thread(()-> {
                fairLock.lock();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    fairLock.unlock();
                }
            },i+"").start();
        }
    }
}
